package com.zwk.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zwk.gulimall.product.annotation.Overall;
import com.zwk.gulimall.product.service.CategoryBrandRelationService;
import com.zwk.gulimall.product.vo.Catelog2Vo;
import org.bouncycastle.util.Strings;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zwk.common.utils.PageUtils;
import com.zwk.common.utils.Query;

import com.zwk.gulimall.product.dao.CategoryDao;
import com.zwk.gulimall.product.entity.CategoryEntity;
import com.zwk.gulimall.product.service.CategoryService;
import org.springframework.util.StringUtils;

import javax.print.attribute.standard.CopiesSupported;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService, ApplicationContextAware {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    private ApplicationContext context;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> findCatelogPath(Long catId) {
        List<CategoryEntity> result = new ArrayList<>();
        findCatelogPath(catId, result);
        return result;
    }

    @Override
    @CacheEvict(cacheNames = "category", allEntries = true)
    public void updateDetail(CategoryEntity categoryEntity) {
        this.updateById(categoryEntity);
        context.publishEvent(categoryEntity);
    }

    @Cacheable(value = {"category"},key = "#root.method.name",sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("getLevel1Categorys........");
        long l = System.currentTimeMillis();
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(
                new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        System.out.println("消耗时间："+ (System.currentTimeMillis() - l));
        return categoryEntities;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList,Long parentCid) {
        List<CategoryEntity> categoryEntities = selectList.stream().filter(item -> item.getParentCid().equals(parentCid)).collect(Collectors.toList());
        return categoryEntities;
        // return this.baseMapper.selectList(
        //         new QueryWrapper<CategoryEntity>().eq("parent_cid", parentCid));
    }

    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        System.out.println("查询了数据库");

        //将数据库的多次查询变为一次
        List<CategoryEntity> selectList = this.list();

        //1、查出所有分类
        //1、1）查出所有一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);

        //封装数据
        Map<String, List<Catelog2Vo>> parentCid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、每一个的一级分类,查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());

            //2、封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName().toString());

                    //1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());

                    if (level3Catelog != null) {
                        List<Catelog2Vo.Category3Vo> category3Vos = level3Catelog.stream().map(l3 -> {
                            //2、封装成指定格式
                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                            return category3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(category3Vos);
                    }

                    return catelog2Vo;
                }).collect(Collectors.toList());
            }

            return catelog2Vos;
        }));

        return parentCid;
    }

    private void findCatelogPath(Long catId, List<CategoryEntity> result) {
        CategoryEntity category = this.getById(catId);
        if (category==null){
            return;
        }
        if (category.getParentCid() == 0) {
            result.add(category);
            return;
        }
        findCatelogPath(category.getParentCid(), result);
        result.add(category);
    }


    /**
     * 获取分类树
     * @return
     */
    @Cacheable(cacheNames="category",key = "'categoryTree'")
    @Override
    public List<CategoryEntity> listWithTree() {
        //todo:存在redis异常（堆外内存溢出异常），产生原因是lettuce的bug
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        //先查询redis
        String categoryTree = operations.get("categoryTree");
        if (StringUtils.isEmpty(categoryTree)){
            //加锁查询数据库
            RLock lock = redissonClient.getLock("tree-lock");
            lock.lock(10, TimeUnit.SECONDS);
            if (StringUtils.isEmpty(categoryTree)){
                List<CategoryEntity> categoryTrees = getTreeFromDB();
                categoryTree = JSON.toJSONString(categoryTrees);
                operations.set("categoryTree",categoryTree);
            }
            lock.unlock();
        }
        List<CategoryEntity> resultTree = JSON.parseObject(categoryTree, new TypeReference<List<CategoryEntity>>() {});
        return resultTree;
    }



    public List<CategoryEntity> getTreeFromDB() {
        List<CategoryEntity> list = this.list();
        List<CategoryEntity> categoryTrees = list.stream().filter(
                categoryEntity -> categoryEntity.getParentCid() == 0
        ).map(categoryEntity -> {
            categoryEntity.setChildren(getCategoryChildren(categoryEntity, list));
            return categoryEntity;
        }).sorted((c1, c2) ->
                (c1.getSort() == null ? 0 : c1.getSort()) - (c2.getSort() == null ? 0 : c2.getSort())
        ).collect(Collectors.toList());
        return categoryTrees;
    }

    /**
     * 查询category的子分类
     * @param category
     * @param list
     * @return
     */
    private List<CategoryEntity> getCategoryChildren(CategoryEntity category, List<CategoryEntity> list) {
        List<CategoryEntity> children = list.stream().filter(c ->
                category.getCatId().equals(c.getParentCid())
        ).map(c -> {
            c.setChildren(getCategoryChildren(c, list));
            return c;
        }).sorted((c1, c2) -> {
            if (c1.getSort() == null || c2 == null) {
                System.out.println();
            }
            return (c1.getSort() == null ? 0 : c1.getSort()) - (c2.getSort() == null ? 0 : c2.getSort());
        }).collect(Collectors.toList());

        return children;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context=applicationContext;
    }
}